<?php
/*=============================================================================
|| ##################################################################
||	phpFoX Konsort
|| ##################################################################
||
||	Copyright		: (C) 2005-2007 PHPFOX Limited a Reality Fox Creation
||	Contact			: info@phpfox.com
||
||	- phpFoX and all of its source code and files are protected by Copyright Laws.
||
||	- The license for phpFoX permits you to install this software on a single domain (.com, .org, .net, etc.).
||
||	- You may also not remove this copyright screen which shows the copyright information and credits for phpFoX (RealityFOX Creations).
||
||	- phpFoX Konsort is NOT a FREE software - http://www.phpfox.com/license/
||
|| ##################################################################
=============================================================================*/

/* $File: ./include/debug.inc.php, $Author:  $ */

/** File contains debugging functions
 * @package debug
 */

if ( isset($_CONF['debug']) && $_CONF['debug'] )
{
	error_reporting(E_ALL);
}
else
{
	error_reporting(0);
}

/** Formats output. Using for debuging
 */
function d($mParam, $bExit = 0, $bVarDump = 0)
{
    echo '<hr><pre>';
    ob_start();
    if (!$bVarDump)
    {
        print_r($mParam);
    }
    else
    {
        var_dump($mParam);
    }
    $sStr = htmlspecialchars(ob_get_contents());
    ob_clean();
    echo $sStr;
    echo '</pre><hr>';
    if ($bExit) exit;
}

function dm($bExit = 0)
{
    echo '<hr><pre>';
    $iMemorySize = _get_memory_usage();
    $sMemorySize = _format_filesize($iMemorySize);
    $sStr = '<b style="color:red;">Memory usage: '.$sMemorySize.'</b>';
    echo $sStr;
    echo '</pre><hr>';
    if ($bExit) exit;
}

/** Sets custom error handler
 */
function errorHandler($nErrNo, $sErrMsg, $sFulename, $nLinenum, $aVars)
{
	if ( defined("phpfoxDevMode") && !phpfoxDevMode )
	{
		if (!error_reporting()) //error reporting has been overriden by '@'
    	{
    	    return;
		}
	}

    if (defined('E_STRICT'))
    {
        if (E_STRICT == $nErrNo)
        {
            return;
        }
    }

    if (substr(PHP_VERSION, 0, 1) < 5)
    {
        $iStart = 1;
    }
    else
    {
        $iStart = 0;
    }

    $aTypes = array (
        1   =>  "Error",
        2   =>  "Warning",
        4   =>  "Parsing Error",
        8   =>  "Notice",
        16  =>  "Core Error",
        32  =>  "Core Warning",
        64  =>  "Compile Error",
        128 =>  "Compile Warning",
        256 =>  "User Error",
        512 =>  "User Warning",
        1024=>  "User Notice",
        2048=>  "PHP 5",
    );

    $aColors = array (
        1   =>  "#FF9999",
        2   =>  "#00FFFF",
        4   =>  "#FF9999",
        8   =>  "#99FF99",
        16  =>  "#FF9999",
        32  =>  "#00FFFF",
        64  =>  "#FF9999",
        128 =>  "#00FFFF",
        256 =>  "#FF9999",
        512 =>  "#00FFFF",
        1024=>  "#FF9999",
        2048=>  "#FF9999",
    );

    $sErr = '<br><table border="0" cellspacing="0" cellpadding="2" style="font-family:Verdana;font-size:12px; border-color: #000000; border: 1px solid black">'.
            '   <tr><td colspan="10"  align="left" valig="top" style="background-color: '.$aColors[$nErrNo].'"><!-- $$$error$$$ --><b>'.$aTypes[$nErrNo].':&nbsp;'.$sErrMsg.'</b></td></tr>';
    $aFiles = debug_backtrace();
    if (isset($aFiles[$iStart]['file']) and strpos($aFiles[$iStart]['file'], '%%') !== false)
    {
        return;
    }
    if (isset($aFiles[$iStart]['file']) and strpos($aFiles[$iStart]['file'], 'Smarty.class.php') !== false)
    {
        return;
    }

    $sPath = "";
    for ($i=$iStart, $n=sizeof($aFiles); $i<$n; ++$i)
    {
        $sArgs = '';
        if (isset($aFiles[$i]['args']))
        {
            $aArgs = array();
            $aArgs = array_merge($aFiles[$i]['args'], array());
            if ($aArgs and is_array($aArgs))
            {
                foreach ($aArgs as $k=>$v)
                {
                    if (is_numeric($v))
                    {
                        $aArgs[$k] = '<span style="color:#7700AA">'.$v.'</span>';
                    }
                    elseif(is_bool($v))
                    {
                        $aArgs[$k] = '<span style="color:#222288;">'.($v ? 'TRUE' : 'FALSE').'</span>';
                    }
                    elseif(is_null($v))
                    {
                        $aArgs[$k] = '<span style="color:#222288;">NULL</span>';
                    }
                    elseif(is_array($v))
                    {
                        $aArgs[$k] = 'Array('.count($v).')';
                    }
                    elseif (is_string($v) &&
                            ! ( ('"'==substr($v,0,1)) && ('"'==substr($v,-1))) )
                    {
                        $aArgs[$k] = '<span style="color:#0000FF">"'.$v.'"</span>';
                    }
                    elseif(is_object($v))
                    {
                        unset($aArgs[$k]);
                        $aArgs[$k] = '{' . ucfirst(get_class($v)) . '}';
                    }
                }
            }
            $sArgs = implode(', ', $aArgs);
        }

        $sFuncName = (isset($aFiles[$i]['class'])?$aFiles[$i]['class']:'').
                     (isset($aFiles[$i]['type'])?$aFiles[$i]['type']:'').
                     $aFiles[$i]['function'].'('.$sArgs.')';
        if ($iStart == $i)
        {
            $sFuncName = '<b>'.$sFuncName.'</b>';
        }
        $sFile = (isset($aFiles[$i]['file']) ? str_replace($sPath, '/', $aFiles[$i]['file']) : '');
        $sErr .= '<tr><td bgcolor="#DDEEFF" align="right">'.$i.'&nbsp;</td>'.
                 '<td>'.$sFile.'&nbsp;:&nbsp;<b>'.(isset($aFiles[$i]['line']) ? $aFiles[$i]['line'] : '').'</b>&nbsp;&nbsp; </td>'.
                 '<td><tt>'.$sFuncName.'</tt></td></tr>';
    }
    $sErr .= '</table>';

    echo $sErr;

	/*
	if ( defined('cachedDir') && class_exists('App') )
	{
		if ( App::getParam('debug_php_log') )
		{
			$sTempFile = cachedDir . "error.log";
			$sWrite = (file_exists($sTempFile) ? file_get_contents($sTempFile) . "\n" . $sErr : $sErr);
    		$hFile = fopen($sTempFile, "w+");
    		fwrite($hFile, $sWrite);
    		fclose($hFile);
		}
	}
	*/

    // Turn on super duper debug mode
    if ( phpfoxDevMode )
    {
    	exit();
    }
}

if ( isset($_CONF['debug']) && $_CONF['debug'] )
{
	set_error_handler('errorHandler');
}

/** Shows sql history for current db connection
 */
function showSql($bReturn = false)
{
    $oDb = & Database::get();
    $fSum = 0.0;
    $fLimit = 0.05*128;
    $tCount = 0;
    $sOut =  '<table width="98%" border="1" cellspacing="0" cellpadding="2" style="margin-left:auto;margin-right:auto;color:black;font-family:verdana;font-size:10pt;background:#fff;">';
    $sOut .= '
    <tr>
    	<td colspan="3" style="background:#000;padding:6px;color:#fff;text-align:center;font-size:14pt;">
    	<b>Developers Debug</b>
    	</td>
    </tr>
    ';

    $sOutExtra = '';
    global $debugTemplate;
    if ( is_array($debugTemplate) )
    {
    	$sOutExtra .= '
    	<tr>
    		<td colspan="3" style="background:#195B85;padding:6px;color:#fff;text-align:left;font-size:12pt;cursor:pointer;" onclick="SwitchMenu3(\'debugTemplateLoad\',\'debugTemplateLoadText\')">
    		<span class="cur" id="debugTemplateLoadText">[-]</span><b>Template Load</b>
    		</td>
    	</tr>
    	<tr id="debugTemplateLoad">
			<td colspan="3" style="padding:6px;text-align:left;font-size:9pt;background:#fff;color:#000;">        	
    	';
	    foreach($debugTemplate as $temps)
	    {
	    	$sOutExtra .= '
			<div style="background:#fff; border-bottom:1px #000 solid; padding:3px; font-size:9pt;">
	    	'. ltrim(str_replace(array(App::getParam('path'), 'design/templates/default'), '', $temps['name']), '/') .' loaded in '. $temps['time'] .'
		    </div>
	    	';
	    }
	    $sOutExtra .= '</td></tr>';
	    if (isset($_COOKIE['debugTemplateLoad']))
	    {
	    	$sOutExtra .= '<script type="text/javascript">SwitchMenu3(\'debugTemplateLoad\',\'debugTemplateLoadText\');</script>';	
	    }	 	    
	}


    global $aFilesIncluded;
    if ( is_array($aFilesIncluded) )
    {
    	$sOutExtra .= '
    	<tr>
    		<td colspan="3" style="background:#195B85;padding:6px;color:#fff;text-align:left;font-size:12pt;cursor:pointer;" onclick="SwitchMenu3(\'debugIncClasses\',\'debugIncClassesText\')">
    		<span class="cur" id="debugIncClassesText">[-]</span><b>Included Classes/Modules</b>
    		</td>
    	</tr>
    	<tr id="debugIncClasses">
			<td colspan="3" style="padding:6px;text-align:left;font-size:9pt;background:#fff;color:#000;">    	
    	';
	    foreach($aFilesIncluded as $temps2)
	    {
	    	$sOutExtra .= '
			<div style="background:#fff; border-bottom:1px #000 solid; padding:3px; font-size:9pt;">
	    	'. $temps2['name'] .' loaded in '. $temps2['time'] .'
		    </div>
	    	';
	    }
	    $sOutExtra .= '</td></tr>';
	    if (isset($_COOKIE['debugIncClasses']))
	    {
	    	$sOutExtra .= '<script type="text/javascript">SwitchMenu3(\'debugIncClasses\',\'debugIncClassesText\');</script>';	
	    }	    
	}

    global $aCacheIncluded;
    if ( is_array($aCacheIncluded) )
    {
    	$sOutExtra .= '
    	<tr>
    		<td colspan="3" style="background:#195B85;padding:6px;color:#fff;text-align:left;font-size:12pt;cursor:pointer;" onclick="SwitchMenu3(\'debugIncCachedFiles\',\'debugIncCachedFilesText\')">
    		<span class="cur" id="debugIncCachedFilesText">[-]</span><b>Included Cached Files</b>
    		</td>
    	</tr>
    	<tr id="debugIncCachedFiles">
			<td colspan="3" style="padding:6px;text-align:left;font-size:9pt;background:#fff;color:#000;">
    	';
	    foreach($aCacheIncluded as $temps3)
	    {
	    	$sOutExtra .= '<div style="background:#fff; border-bottom:1px #000 solid; padding:3px; font-size:9pt;">'. str_replace(array(App::getParam('path'), 'file/cache/'), '', $temps3['name']) .' loaded in '. $temps3['time'] .'</div>';
	    }
	    $sOutExtra .= '</td></tr>';
	    if (isset($_COOKIE['debugIncCachedFiles']))
	    {
	    	$sOutExtra .= '<script type="text/javascript">SwitchMenu3(\'debugIncCachedFiles\',\'debugIncCachedFilesText\');</script>';	
	    }
	}
	
    global $aLanguageGroups;
    if ( is_array($aLanguageGroups) )
    {
    	$sOutExtra .= '
    	<tr>
    		<td colspan="3" style="background:#195B85;padding:6px;color:#fff;text-align:left;font-size:12pt;cursor:pointer;" onclick="SwitchMenu3(\'debugLangGroups\',\'debugLangGroupsText\')">
    		<span class="cur" id="debugLangGroupsText">[-]</span><b>Included Language Groups</b>
    		</td>
    	</tr>
    	<tr id="debugLangGroups">
			<td colspan="3" style="padding:6px;text-align:left;font-size:9pt;background:#fff;color:#000;">    	
    	';
	    foreach($aLanguageGroups as $temps4)
	    {
	    	$sOutExtra .= '
			<div style="background:#fff; border-bottom:1px #000 solid; padding:3px; font-size:9pt;">
	    	'. $temps4['name'] .' loaded in '. $temps4['time'] .'
		    </div>
	    	';
	    }
	    $sOutExtra .= '</td></tr>';
	    if (isset($_COOKIE['debugLangGroups']))
	    {
	    	$sOutExtra .= '<script type="text/javascript">SwitchMenu3(\'debugLangGroups\',\'debugLangGroupsText\');</script>';	
	    }	    
	}

    global $aLanguageVars;
    if ( is_array($aLanguageVars) )
    {
    	$sOutExtra .= '
    	<tr>
    		<td colspan="3" style="background:#195B85;padding:6px;color:#fff;text-align:left;font-size:12pt;cursor:pointer;" onclick="SwitchMenu3(\'debugLangVar\',\'debugLangVarText\')">
    		<span class="cur" id="debugLangVarText">[-]</span><b>Language Vars</b>
    		</td>
    	</tr>
    	<tr id="debugLangVar">
			<td colspan="3" style="padding:6px;text-align:left;font-size:9pt;background:#fff;color:#000;">    	
    	';
	    foreach($aLanguageVars as $temps5)
	    {
	    	$sOutExtra .= '
			<div style="background:#fff; border-bottom:1px #000 solid; padding:3px; font-size:9pt;">
	    	'. $temps5['name'] .' = ' . htmlspecialchars($temps5['phrase']) . '
		   	</div>
	    	';
	    }	
	    $sOutExtra .= '</td></tr>';
	    if (isset($_COOKIE['debugLangVar']))
	    {
	    	$sOutExtra .= '<script type="text/javascript">SwitchMenu3(\'debugLangVar\',\'debugLangVarText\');</script>';	
	    }
	}	
	
    global $aCalledHooks;
    if ( is_array($aLanguageVars) )
    {
    	$sOutExtra .= '
    	<tr>
    		<td colspan="3" style="background:#195B85;padding:6px;color:#fff;text-align:left;font-size:12pt;cursor:pointer;" onclick="SwitchMenu3(\'debugHooks\',\'debugHooksText\')">
    		<span class="cur" id="debugHooksText">[-]</span><b>Available Hooks</b>
    		</td>
    	</tr>
    	<tr id="debugHooks">
			<td colspan="3" style="padding:6px;text-align:left;font-size:9pt;background:#fff;color:#000;">
    	';
	    foreach($aCalledHooks as $temps6)
	    {
	    	$sOutExtra .= '
			<div style="background:#fff; border-bottom:1px #000 solid; padding:3px; font-size:9pt;">
	    	'. $temps6 .'
		   	</div>
	    	';
	    }	
	    $sOutExtra .= '</td></tr>';
	    if (isset($_COOKIE['debugHooks']))
	    {
	    	$sOutExtra .= '<script type="text/javascript">SwitchMenu3(\'debugHooks\',\'debugHooksText\');</script>';	
	    }    
	}		

	if ( isset($oDb->CachedQueryRow) && is_array($oDb->CachedQueryRow) )
	{
    	$sOutExtra .= '
    	<tr>
    		<td colspan="3" style="background:#195B85;padding:6px;color:#fff;text-align:left;font-size:12pt;cursor:pointer;" onclick="SwitchMenu3(\'debugCachedQueries\',\'debugCachedQueriesText\')">
    		<span class="cur" id="debugCachedQueriesText">[-]</span><b>SQL Cached Queries</b>
    		</td>
    	</tr>
    	<tr id="debugCachedQueries">
			<td colspan="3" style="padding:6px;text-align:left;font-size:9pt;background:#fff;color:#000;">    	
    	';
    	if ( count($oDb->CachedQueryRow) > 0 )
    	{
			foreach($oDb->CachedQueryRow as $sCachedRowQuery)
			{
	    		$sOutExtra .= '
				<div style="background:#fff; border-bottom:1px #000 solid; padding:3px; font-size:9pt;">
					'. htmlspecialchars($sCachedRowQuery) .'
			    </div>
	    		';
			}
		}
		else
		{
			$sOutExtra .= '
				<div style="background:#fff; border-bottom:1px #000 solid; padding:3px; font-size:9pt;">
					No Cached Queries
				</div>
	    		';
	    }	    
	    $sOutExtra .= '</td></tr>';
	    if (isset($_COOKIE['debugCachedQueries']))
	    {
	    	$sOutExtra .= '<script type="text/javascript">SwitchMenu3(\'debugCachedQueries\',\'debugCachedQueriesText\');</script>';	
	    }   
	}

    $sOutExtra .= '
    <tr>
    	<td colspan="3" style="background:#195B85;padding:6px;color:#fff;text-align:left;font-size:12pt;cursor:pointer;" onclick="SwitchMenu3(\'debugSQLQueries\',\'debugSQLQueriesText\')">
    	<span class="cur" id="debugSQLQueriesText">[-]</span><b>SQL Queries</b>
    	</td>
    </tr>
    <tr id="debugSQLQueries">
		<td colspan="3" style="padding:6px;text-align:left;font-size:9pt;background:#fff;color:#000;">      
	<table width="99%" border="1" cellspacing="0" cellpadding="2" style="margin-left:auto;margin-right:auto;color:black;font-family:verdana;font-size:10pt;">
    ';
    $aKeywords = array('SELECT ', 'FROM ', 'WHERE ', 'UPDATE ', ' AS ', 'INNER JOIN ', 'LEFT JOIN ', 'INSERT INTO ', 'SHOW COLUMNS ');
    $aReplaces = array_map('_addKeyworSyntax', $aKeywords);
    foreach($oDb->aHistory as $aLine)
    {
    	$tCount++;
        $sColor = sprintf('%02X', min(255, $fLimit/$aLine['time']));
        $aLine['sql'] = str_replace($aKeywords, $aReplaces, $aLine['sql']);

    		$sExtra = '';
    		$newSql = str_replace(array('<b>','</b>'), '', $aLine['sql']);
    	    if ( substr(trim($newSql), 0, 6) == 'SELECT' )
    	    {
    	    	$iDivWidth = '16%';
    	    	$aExplains = $oDb->getRows("EXPLAIN " . $newSql);
    	    	$sExtra .= '<br /><br /><table style="background:#54A4DE; border:1px #000 solid; width:100%;" cellpadding="2" cellspacing="2"><tr><td style="background:#195B85; color:#fff; font-weight:bold;" colspan="10">SQL EXPLAIN</td></tr><tr>';
    	    	$iCnt = 0;
    	    	foreach( $aExplains as $aExplain )
    	    	{
    	    		$iCnt++;
    	    		if ( $iCnt == 1 )
    	    		{
    	    			foreach( $aExplain as $k => $v )
    	    			{
    	    				$sExtra .= '<th style="background:#000000; color:#fff;">&nbsp;'. $k .'</th>';
    	    			}
    	    		}

    	    		$sExtra .= '</tr><tr>';
    	    		foreach( $aExplain as $k => $v )
    	    		{
       	    			$sExtra .= '<td style="background:#FFFFFF;"> &nbsp;'. str_replace(App::getParam('db', 'prefix'), '', $v) .'</td>';
    	    		}
    	    	}
    	    	$sExtra .= '</tr></table><br /><br />';
    	    }		

  		$sOutExtra .= '<tr><td width="1%" align="left" valign="top" style="background-color: #FF'.$sColor.$sColor.'">'.sprintf('%0.7f', $aLine['time']).'</td><td align="left" valign="top" style="background:#fff;">
     			'. $aLine['sql'] .'' . $sExtra . '
     			</td><td style="background:#fff;">'.$aLine['rows'].'</td></tr>';
		
        $fSum += $aLine['time'];
    }
	$sOutExtra .= '</table></td></tr>';
	if (isset($_COOKIE['debugSQLQueries']))
	{
		$sOutExtra .= '<script type="text/javascript">SwitchMenu3(\'debugSQLQueries\',\'debugSQLQueriesText\');</script>';	
	}    
    
    $sOut .= '
    <tr>
    	<td colspan="3" style="background:#195B85;padding:6px;color:#fff;text-align:left;font-size:12pt;cursor:pointer;" onclick="SwitchMenu3(\'debugData\',\'debugDataText\')">
    	<span class="cur" id="debugDataText">[-]</span><b>Debug Data</b>
    	</td>
    </tr>    
    <tr id="debugData">
		<td colspan="3" style="padding:6px;text-align:left;font-size:9pt;background:#fff;color:#000;">      
		<b>Page loaded in:</b> ' . PHPFOX_PAGE_LOAD . '
		<br />
		<b>Total SQL Time:</b> '.sprintf('%0.7f',$fSum).'
		<br />
		<b>Total SQL Queries:</b> '. $tCount .' <br />
		';
	$iMemoryUsage = _get_memory_usage();
    $sMemoryUsage = _format_filesize($iMemoryUsage);
    
    if (!isset($_SESSION['checkImageMagick']))
    {
		$sIMPath = App::getParam('image.im.path');
		$bIMExist = true;
    	if (!$sIMPath)
    	{
    		$bIMExist = false;
		}
		if (!@file_exists($sIMPath))
		{
			$sSearch = App::executeCommand('whereis convert');
			$aPart = explode(" ", $sSearch);
			if (isset($aPart[1]) && file_exists($aPart[1]))
			{
				$sIMPath = $aPart[1];
			}
			else 
			{
				$bIMExist = false;                                
			}
		}
		if (!@is_executable($sIMPath))
    	{
			$bIMExist = false;                
		}
		if ($bIMExist)
		{
    		$sResult = App::executeCommand($sIMPath);
    		if (!$sResult)
    		{
				$bIMExist = false;               
			}
		}
		
		$_SESSION['checkImageMagick'] = $bIMExist;
    }
	$bIMExist = (isset($_SESSION['checkImageMagick']) ? $_SESSION['checkImageMagick'] : $bIMExist);

    $sOut .= '
		<b>Total memory usage:</b> '.$sMemoryUsage.' <br />
		<b>ImageMagick Support:</b> ' . ($bIMExist ? 'Yes' : 'No') . ' <br />
		<b>Image Processing Library:</b> ' . (App::getParam('image.im.use') ? 'ImageMagick' : 'GD') . ' <br />
		</td>
	</tr>	
	';
	if (isset($_COOKIE['debugData']))
	{
		$sOutExtra .= '<script type="text/javascript">SwitchMenu3(\'debugData\',\'debugDataText\');</script>';	
	}      
    
    $sOut .= '' . $sOutExtra . '
    <tr>
    	<td colspan="3" style="background:#195B85;padding:6px;color:#fff;text-align:left;font-size:12pt;cursor:pointer;" onclick="SwitchMenu3(\'debugSessions\',\'debugSessionsText\')">
    	<span class="cur" id="debugSessionsText">[-]</span><b>Sessions and Cookies</b>
    	</td>
    </tr>
    ';
    $sOut .= '
    <tr id="debugSessions">
		<td colspan="3" style="padding:6px;text-align:left;font-size:9pt;background:#fff;color:#000;">  
	';
	if ( isset($_SESSION) )
	{
    	$sOut .= "<b>Sessions:</b><pre>" . print_r($_SESSION, true) . "</pre>";
	}
	if ( isset($_COOKIE) )
	{
    	$sOut .= "<b>Cookies:</b><pre>" . print_r($_COOKIE, true) . "</pre>";
	}

	$sOut .= '
		</td>
	</tr></table>
	';	
	if (isset($_COOKIE['debugSessions']))
	{
		$sOut .= '<script type="text/javascript">SwitchMenu3(\'debugSessions\',\'debugSessionsText\');</script>';	
	}   	

	if ( $bReturn )
	{
		return $sOut;
	}

	print $sOut;
}

function _addKeyworSyntax($sVal)
{
    return '<b>'.$sVal.'</b>';
}

function _get_memory_usage()
{
    if (function_exists('memory_get_usage'))
    {
        return memory_get_usage();
    }
    if (stristr(PHP_OS, "win"))
    {
     	return 'Not Supported';
    	$output = array();
        exec( 'tasklist /FI "PID eq ' . getmypid() . '" /FO LIST', $output );
        return preg_replace( '/[\D]/', '', $output[5] ) * 1024;
    }
}

function _format_filesize($iSize, $iPrecision = 2)
{
    if (!is_numeric($iSize))
        return $iSize;

    if (!is_numeric($iPrecision))
        $iPrecision = 2;
    $sSize   = '';
    $fSize   = 0;
    $sSuffix = '';

    if ($iSize >= 1073741824)
    {
        $fSize = $iSize / 1073741824;
        $sSuffix = 'Gb';
    }
    elseif (($iSize >= 1048576) && ($iSize < 1073741824))
    {
        $fSize = $iSize / 1048576;
        $sSuffix = 'Mb';
    }
    elseif (($iSize >= 1024) && ($iSize < 1048576))
    {
        $fSize = $iSize / 1024;
        $sSuffix = 'kb';
    }
    else
    {
        $fSize = $iSize;
        $sSuffix = 'b';
    }
    $sSize = round($fSize, $iPrecision);
    $sSize .= ' '.$sSuffix;
    return $sSize;
}

?>